#include <func.h>

// 服务端

typedef struct
{
    char file_name[64];
} fileName_t;

int main(void)
{   
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1)
        error(1, errno, "socket");

    int reuse = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "bind");
    
    if(listen(fd, 10) == -1)
        error(1, errno, "listen");

    int sock_fd = accept(fd, NULL, NULL);

    int file_fd = open("a.mp4", O_RDWR);
    if(file_fd == -1)
        error(1, errno, "open");
    
    struct stat statbuf;
    if(fstat(file_fd, &statbuf) == -1)
        error(1, errno, "fstat");

    fileName_t file_name;
    strcpy(file_name.file_name, "a.mp4");
    // 发送文件名
    if(send(sock_fd, &file_name, sizeof(file_name), MSG_NOSIGNAL) == -1)
        error(1, errno, "send");  

    // 发送文件信息
    if(send(sock_fd, &statbuf, sizeof(statbuf), MSG_NOSIGNAL) == -1)
        error(1, errno, "send");   

    while(1)
    {
        char buf[1024] = {0};
        int count = read(file_fd, buf, sizeof(buf));
        if(count == 0)
            break;
        if(send(sock_fd, buf, count, MSG_NOSIGNAL) == -1)
            error(1, errno, "send");
    }

    system("sha1sum a.mp4");
    close(file_fd);
    close(sock_fd);
    close(fd);
    return 0;
}

